package com.aphrodite.io.sip.header;

import java.util.Date;

import com.aphrodite.io.sip.provider.SipParser;
import com.aphrodite.util.StringParser;

/**
 * SIP Header Expires.
 * <p>
 * Note: for backward compatibility with legacy implementations the date format
 * is still supported although it has been deprecated in RFC 3261.
 */
public final class ExpiresHeader extends SipDateHeader {
	// public ExpiresHeader()
	// { super(SipHeaders.Expires);
	// }

	/** Creates a new ExpiresHeader based on a Date value. */
	public ExpiresHeader(Date date) {
		super(SipHeaders.Expires, date);
	}

	public ExpiresHeader(Header hd) {
		super(hd);
	}

	/** Creates a new ExpiresHeader with delta-seconds as value. */
	public ExpiresHeader(int seconds) {
		super(SipHeaders.Expires, (String) null);
		value = String.valueOf(seconds);
	}

	public ExpiresHeader(String hvalue) {
		super(SipHeaders.Expires, hvalue);
	}

	/** Gets value of ExpiresHeader as absolute date */
	public Date getDate() {
		Date date = null;
		if (isDate()) {
			date = (new SipParser((new StringParser(value)).getStringUnquoted())).getDate();
		} else {
			long secs = getDeltaSeconds();
			if (secs >= 0)
				date = new Date(System.currentTimeMillis() + secs * 1000);
		}
		return date;
	}

	/** Gets value of ExpiresHeader as delta-seconds */
	public int getDeltaSeconds() {
		int secs = -1;
		if (isDate()) {
			Date date = (new SipParser((new StringParser(value)).getStringUnquoted())).getDate();
			secs = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
			if (secs < 0)
				secs = 0;
		} else
			secs = (new SipParser(value)).getInt();

		return secs;
	}

	/**
	 * Gets boolean value to indicate if expiry value of ExpiresHeader is in
	 * date format.
	 */
	public boolean isDate() {
		if (value.indexOf("GMT") >= 0)
			return true;
		return false;
	}

	/** Sets expires of ExpiresHeader as delta-seconds */
	// public void setDeltaSeconds(long seconds)
	// { value=String.valueOf(seconds);
	// }
	/** Gets value of ExpiresHeader */
	/*
	 * public static void getExpires(ExpiresHeader eh) { if (eh.isDate())
	 * eh.getDate(); else eh.getDeltaSeconds(); }
	 */
}
